package main

import (
	"context"
	"fmt"
	"log"
	"mxshop_srvs/user_srv/proto"
	"strconv"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var (
	userClient proto.UserClient
	conn       *grpc.ClientConn
)

// Init 初始化 gRPC 客户端
func Init() {
	var err error
	conn, err = grpc.Dial("localhost:50053", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("Failed to connect to gRPC server: %v", err)
	}
	userClient = proto.NewUserClient(conn)
}

// TestGetUserListAndCheckPassword 获取用户列表并校验密码
func TestGetUserListAndCheckPassword() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	// 获取用户列表
	list, err := userClient.GetUserList(ctx, &proto.PageInfo{
		Pn:    1,
		PSize: 10,
	})
	if err != nil {
		log.Printf("Failed to fetch user list: %v", err)
		return
	}

	// 遍历用户列表并校验密码
	for _, user := range list.Data {
		fmt.Printf("User: %s, Nickname: %s, Password: %s\n", user.Mobile, user.NickName, user.PassWord)

		check, err := userClient.CheckPassWord(ctx, &proto.CheckPassWordInfo{
			Password:          "admin123",
			EncryptedPassword: user.PassWord,
		})
		if err != nil {
			log.Printf("Failed to check password for user %s: %v", user.Mobile, err)
			continue
		}
		fmt.Printf("Password valid: %v\n", check.Success)
	}
}

// TestCreateUser 测试创建用户
func TestCreateUser() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	for i := range 10 {
		rsp, err := userClient.CreateUser(ctx, &proto.CreateUserInfo{
			NickName: fmt.Sprintf("Seina%d", i),
			Mobile:   fmt.Sprintf("1567547771%d", i),
			PassWord: "admin123",
		})
		if err != nil {
			panic(err)
		}
		fmt.Printf("Create user success: %v\n", rsp.Id)
	}
}

// TestGetUserByMobile 测试根据手机号获取用户信息
func TestGetUserByMobile() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	user, err := userClient.GetUserByMobile(ctx, &proto.MobileRequest{Mobile: "15675477711"})
	if err != nil {
		panic(err)
	}
	fmt.Printf("User info: %v\n", user)
}

// TestGetUserById 测试根据id获取用户信息
func TestGetUserById() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	user, err := userClient.GetUserById(ctx, &proto.IdRequest{Id: strconv.Itoa(1)})
	if err != nil {
		panic(err)
	}
	fmt.Printf("User info: %v\n", user.NickName)
}
func TestUpdateUser() {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	_, err := userClient.UpdateUser(ctx, &proto.UpdateUserInfo{
		Id:       1,
		NickName: "Seina666",
		Gender:   "female",
	})
	if err != nil {
		panic(err)
	}
	TestGetUserById()
}

func main() {
	Init()
	TestUpdateUser()
	defer conn.Close() // 延迟关闭连接
}
